/**
 * 功能:TK_OUT_WAREHOUSE 控制器类
 * 开发人员:yaren
 * 创建时间:2012/4/22 12:15:56
 */
package com.towker.frame.controller.warehouse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.towker.web.MyRequest;
import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.core.util.StringUtil;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Goods;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.InWarehouse;
import com.towker.frame.model.warehouse.OutWarehouse;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.model.warehouse.WarehouseAccounts;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.GoodsService;
import com.towker.frame.service.basicData.SurplusOrderService;
import com.towker.frame.service.sell.RefGoodsService;
import com.towker.frame.service.warehouse.OutWarehouseService;
import com.towker.frame.service.warehouse.WarehouseAccountsService;
import com.towker.frame.share.sys.user.UserShare;

//TK_OUT_WAREHOUSE
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/warehouse")
public class OutWarehouseController extends BaseController
{
	private OutWarehouseService service;
	private DepartmentsService departmentsService;//部门信息
	private DepotsService depotsService;//仓库信息
	private GoodsService goodsService;//物品信息
	private WarehouseAccountsService warehouseAccountsService;
	private SurplusOrderService surplusOrderService;

	//业务对象注入
	public void setOutWarehouseService(OutWarehouseService service)
	{
		this.service = service;
	}
	public void setDepartmentsService(DepartmentsService departmentsService)
	{
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService)
	{
		this.depotsService = depotsService;
	}
	
	
	public void setGoodsService(GoodsService goodsService)
	{
		this.goodsService = goodsService;
	}
	
	public void setWarehouseAccountsService(WarehouseAccountsService warehouseAccountsService)
	{
		this.warehouseAccountsService = warehouseAccountsService;
	}

	public void setSurplusOrderService(SurplusOrderService surplusOrderService) {
		this.surplusOrderService = surplusOrderService;
	}
	//添加
	@RequestMapping("/addOutWarehouse{viewName}")
	public ModelAndView addOutWarehouse(HttpServletResponse response,HttpServletRequest request, OutWarehouse po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("out_warehouse_code", service.getNewOutCode());//出仓单号
			result.setViewName("/manage/warehouse/addOutWarehouse.jsp");
		}
		else if ("2".equals(viewName))
		{
			po.setCreater_code(UserShare.getCurrentUserCode(request)+"["+UserShare.getCurrentUserName(request)+"]");//获取当前用户代码 名称
			po.setCreater_id(UserShare.getCurrentUserId(request).intValue());//获取当前用户id
			po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
			//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
			
			PrintWriter writer = response.getWriter();
			MyRequest myRequest = new MyRequest(request);
			String goodsInfo = myRequest.getString("goodsInfo");
			try
			{
				service.add(po);
				processRefGoods(request, RefGoodsType.OUTWAREHOUSE_GOODS, po.getId(), goodsInfo);
				//处理库存量,减少
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),po.getId() );

				calcGoodsStock(new ArrayList<RefGoods>(), refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), false, true);
				
				writer.write("添加出仓单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加出仓单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delOutWarehouse")
	public void delOutWarehouse(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		
		long[] ids = req.getLongArray("keyIndex", 0);
		
		for (Long id : ids) {
			OutWarehouse w = service.getById(id);
			if (w != null) {
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(), id.intValue());
				calcGoodsStock(refOldGoods, new ArrayList<RefGoods>(), surplusOrderService, w.getDepot_code(), w.getAuthCoCode(), true, true);
			}
		}
		
		service.delByIds(CollectionUtil.toLongArray(ids));
		
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updOutWarehouse{viewName}")
	public ModelAndView updOutWarehouse(HttpServletRequest request, HttpServletResponse response, OutWarehouse po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			result.setViewName("/manage/warehouse/updOutWarehouse.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			String goodsInfo = req.getString("goodsInfo");
			try
			{
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),po.getId() );
				service.update(po);
				processRefGoods(request, RefGoodsType.OUTWAREHOUSE_GOODS, po.getId(), goodsInfo);
				//处理库存量,减少
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),po.getId() );

				calcGoodsStock(refOldGoods, refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), false, true);
				
				writer.write("修改出仓单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改出仓单失败！" + e.getCause());
			}
		}
		return result;
	}

	//获得分页
	@RequestMapping("/getOutWarehouse")
	public ModelAndView getOutWarehouse(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<OutWarehouse> pageModel = service.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		Map deportMap = new HashMap();
		List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
		result.addObject("deportList", deportList);
		result.setViewName("/manage/warehouse/getOutWarehouse.jsp");
		return result;
	}

	//明细
	@RequestMapping("/getOutWarehouseById")
	public ModelAndView getOutWarehouseById(HttpServletRequest request, HttpServletResponse response)
	{
		OutWarehouse po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("dep", departmentsService.getByCode(po.getDep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		result.setViewName("/manage/warehouse/getOutWarehouseById.jsp");
		result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		return result;
	}
	
	//审核
	@RequestMapping("/auditOutWarehouse{viewName}")
	public ModelAndView auditOutWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		OutWarehouse po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if ("1".equals(viewName)) {
			result = new ModelAndView();
			result.addObject("po", po);
			result.addObject("audit", "audit");
			result.setViewName("/manage/warehouse/getOutWarehouseById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if ("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setAudit_status(1);
				service.update(po);
				
				this.Bookkeeping(po);
				writer.write("审核成功！");
			} catch (Exception e) {
				e.printStackTrace();
				writer.write("审核失败！"+e.getCause());
			}
		}
		return result;
	}
	
	/*//记账
	@RequestMapping("/accOutWarehouse{viewName}")
	public ModelAndView accOutWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		OutWarehouse po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if ("1".equals(viewName)) {
			result = new ModelAndView();
			result.addObject("po", po);
			result.addObject("acc", "acc");
			result.setViewName("/manage/warehouse/getOutWarehouseById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if ("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setAcc_status(1);
				service.update(po);
				List<RefGoods> refgoodList = refGoodsService.getByInfoType(RefGoodsType.OUTWAREHOUSE_GOODS.getValue(), po.getId());
				if (refgoodList!=null && refgoodList.size()!=0) {
					for (int i = 0; i < refgoodList.size(); i++) {
						*//**
						 * 减少库存数量
						 *//*
						RefGoods refGoods = (RefGoods)refgoodList.get(i);
						Goods goods = goodsService.getById(new Long(refGoods.getGoods_id()));
						//更新库存数量
						double stock = goods.getStock()-refGoods.getAmount();
						goods.setStock(stock);
						goodsService.update(goods);
						*//**
						 * 记录到仓库帐中
						 *//*
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WarehouseAccounts warehouseAccounts = new WarehouseAccounts();
						warehouseAccounts.setAcc_period(po.getAcc_period());//财务统计核算期
						warehouseAccounts.setInfo_type("出仓单");//仓库帐类型
						warehouseAccounts.setGoods_sn(goods.getGoods_sn());//物料代码
						warehouseAccounts.setDep_code(po.getDepot_code());//仓库代码
						warehouseAccounts.setCreate_date(po.getOut_date());//入仓单日期
						warehouseAccounts.setCreate_time(po.getOut_time());//入仓库时间
						warehouseAccounts.setSys_date(format.format(new Date()));//生成仓库帐时间
						warehouseAccounts.setAmount(refGoods.getAmount());//物品数量
						warehouseAccounts.setStock_num(stock);//当前库存数量
						warehouseAccounts.setSend_amount(0);//已下采购单要求送货数量, 根据采购单号 查询采购数量
						String remark = "单号："+po.getOut_warehouse_code()+"，部门："+po.getDep_code()+"";
						warehouseAccounts.setRemark(remark);//凭证号（单号）、部门、客户等>
						warehouseAccountsService.add(warehouseAccounts);
					}
				}
				writer.write("记账成功！");
			} catch (Exception e) {
				e.printStackTrace();
				writer.write("记账失败！"+e.getCause());
			}
		}
		return result;
	}*/
	
	
	/**
	 *记账
	 */
	private void Bookkeeping(OutWarehouse po){
		calcWarehouseAccount(warehouseAccountsService, RefGoodsType.OUTWAREHOUSE_GOODS, po.getId(), po.getDepot_code(), po.getAuthCoCode(), false);
	}
	
}
